package shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.List;

/**
 * @author lzh
 * @description
 * @date 2021/2/14
 */
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    public GlobalExceptionHandler() {
        super();
    }

    @ExceptionHandler(value = Exception.class)
    public R exception(Exception e) {
        return R.fail(500, e.getMessage());
    }

    @ExceptionHandler(value = AuthenticationException.class)
    public R exception2(Exception e) {
        return R.fail(401, e.getMessage());
    }

    @ExceptionHandler(value = UnauthorizedException.class)
    public R exception3(Exception e) {
        return R.fail(403, "权限不足，无法操作");
    }

    @ExceptionHandler(value = UnauthenticatedException.class)
    public R exception4(Exception e) {
        return R.fail(401, "未登录，请先登录");
    }

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
            request.setAttribute("javax.servlet.error.exception", ex, 0);
        }
        return new ResponseEntity(R.fail(status.value(), ex.getMessage()), headers, status);
    }

}
